package com.powergisol.gis.gzip;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

public class MyCompressResponse extends HttpServletResponseWrapper {
    private HttpServletResponse response; //接受一个response对象，将对其进行增强
    private ByteArrayOutputStream bout = new ByteArrayOutputStream(); //缓存流，所有响应内容将会被输出到此

    public MyCompressResponse(HttpServletResponse response) {
        super(response);
        // TODO Auto-generated constructor stub
        this.response = response;
    }

    /* (non-Javadoc)
     * @see javax.servlet.ServletResponseWrapper#getOutputStream()
     */
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        // TODO Auto-generated method stub
        return new MyOutputStream(bout); //重写getOutputStream方法
    }


    public byte[] getBuffer(){
        if(bout!=null){
            return bout.toByteArray();//将缓存返回
        }

        return null;
    }
    class MyOutputStream extends ServletOutputStream{
        private ByteArrayOutputStream bout;


        @Override
        public void write(int b) throws IOException {
            // TODO Auto-generated method stub
            bout.write(b); //将响应内容写到bout缓存流中
        }

        public MyOutputStream(ByteArrayOutputStream bout){
            this.bout = bout;

        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener listener) {

        }
    }
}
